import React, { useState } from 'react';
import { Form, Input, Button, Card, Typography, message, Divider, Steps } from 'antd';
import { UserOutlined, LockOutlined, MailOutlined, GiftOutlined, SafetyCertificateOutlined } from '@ant-design/icons';
import { Link, useNavigate } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';
import { RegisterRequest } from '../types';

const { Title, Text } = Typography;
const { Step } = Steps;

const Register: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [verifyLoading, setVerifyLoading] = useState(false);
  const [currentStep, setCurrentStep] = useState(0);
  const [registrationData, setRegistrationData] = useState<RegisterRequest | null>(null);
  const { register, verifyEmailAndLogin } = useAuth();
  const navigate = useNavigate();

  const onFinish = async (values: RegisterRequest) => {
    setLoading(true);
    try {
      const success = await register(values);
      if (success) {
        setRegistrationData(values);
        setCurrentStep(1); // 进入邮箱验证步骤
      }
    } catch (error) {
      message.error('注册失败');
    } finally {
      setLoading(false);
    }
  };

  const onVerifyEmail = async (values: { verificationCode: string }) => {
    setVerifyLoading(true);
    try {
      const success = await verifyEmailAndLogin(values.verificationCode);
      if (success) {
        navigate('/');
      }
    } catch (error) {
      message.error('验证失败，请检查验证码');
    } finally {
      setVerifyLoading(false);
    }
  };

  return (
    <div style={{ 
      minHeight: '100vh', 
      display: 'flex', 
      alignItems: 'center', 
      justifyContent: 'center',
      background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)'
    }}>
      <Card style={{ width: 400, boxShadow: '0 4px 12px rgba(0,0,0,0.15)' }}>
        <div style={{ textAlign: 'center', marginBottom: 24 }}>
          <Title level={2} style={{ color: '#1890ff', marginBottom: 8 }}>
            {currentStep === 0 ? '加入PT站点' : '验证邮箱'}
          </Title>
          <Text type="secondary">
            {currentStep === 0 ? '创建您的账户，开始分享之旅' : '请输入邮箱收到的验证码'}
          </Text>
        </div>

        <Steps current={currentStep} style={{ marginBottom: 24 }}>
          <Step title="填写信息" icon={<UserOutlined />} />
          <Step title="验证邮箱" icon={<SafetyCertificateOutlined />} />
        </Steps>

        {currentStep === 0 ? (
          <Form
            name="register"
            onFinish={onFinish}
            autoComplete="off"
            size="large"
          >
            <Form.Item
              name="username"
              rules={[
                { required: true, message: '请输入用户名!' },
                { min: 3, message: '用户名至少3个字符!' },
                { max: 20, message: '用户名最多20个字符!' }
              ]}
            >
              <Input 
                prefix={<UserOutlined />} 
                placeholder="用户名" 
              />
            </Form.Item>

            <Form.Item
              name="email"
              rules={[
                { required: true, message: '请输入邮箱!' },
                { type: 'email', message: '请输入有效的邮箱地址!' }
              ]}
            >
              <Input 
                prefix={<MailOutlined />} 
                placeholder="邮箱地址" 
              />
            </Form.Item>

            <Form.Item
              name="password"
              rules={[
                { required: true, message: '请输入密码!' },
                { min: 6, message: '密码至少6个字符!' }
              ]}
            >
              <Input.Password
                prefix={<LockOutlined />}
                placeholder="密码"
              />
            </Form.Item>

            <Form.Item
              name="confirmPassword"
              dependencies={['password']}
              rules={[
                { required: true, message: '请确认密码!' },
                ({ getFieldValue }) => ({
                  validator(_, value) {
                    if (!value || getFieldValue('password') === value) {
                      return Promise.resolve();
                    }
                    return Promise.reject(new Error('两次输入的密码不一致!'));
                  },
                }),
              ]}
            >
              <Input.Password
                prefix={<LockOutlined />}
                placeholder="确认密码"
              />
            </Form.Item>

            <Form.Item
              name="invitationCode"
              rules={[{ required: true, message: '请输入邀请码!' }]}
            >
              <Input 
                prefix={<GiftOutlined />} 
                placeholder="邀请码" 
              />
            </Form.Item>

            <Form.Item>
              <Button 
                type="primary" 
                htmlType="submit" 
                loading={loading}
                block
                style={{ height: 40 }}
              >
                注册
              </Button>
            </Form.Item>
          </Form>
        ) : (
          <Form
            name="verify"
            onFinish={onVerifyEmail}
            autoComplete="off"
            size="large"
          >
            <div style={{ textAlign: 'center', marginBottom: 16 }}>
              <Text type="secondary">
                验证码已发送至：{registrationData?.email}
              </Text>
            </div>

            <Form.Item
              name="verificationCode"
              rules={[
                { required: true, message: '请输入验证码!' },
                { len: 6, message: '验证码为6位字符!' }
              ]}
            >
              <Input 
                prefix={<SafetyCertificateOutlined />} 
                placeholder="请输入6位验证码"
                maxLength={6}
              />
            </Form.Item>

            <Form.Item>
              <Button 
                type="primary" 
                htmlType="submit" 
                loading={verifyLoading}
                block
                style={{ height: 40 }}
              >
                验证邮箱
              </Button>
            </Form.Item>

            <Form.Item>
              <Button 
                type="link" 
                onClick={() => setCurrentStep(0)}
                block
              >
                返回修改信息
              </Button>
            </Form.Item>
          </Form>
        )}

        <Divider>或</Divider>

        <div style={{ textAlign: 'center' }}>
          <Text>已有账户？</Text>
          <Link to="/login" style={{ marginLeft: 8 }}>
            立即登录
          </Link>
        </div>

        <Divider />

        <div style={{ textAlign: 'center' }}>
          <Text type="secondary" style={{ fontSize: 12 }}>
            请联系管理员获取邀请码
          </Text>
        </div>
      </Card>
    </div>
  );
};

export default Register; 